from .base_strategy import BaseStrategy
import backtrader as bt
import indicator.MyTTIndicator as Mytt
class MyStrategy(BaseStrategy):
    params = (
        ('fast_period', 5),   # 快速均线周期
        ('slow_period', 20),  # 慢速均线周期
        ('slow_period2', 200),  # 慢速均线周期
    )
 
    def __init__(self):
        super().__init__()

        self.init_indicators()
        # 用于跟踪订单
        self.order = None
    
    def init_indicators(self):
        """在此定义指标 (EMA/MACD/RSI等)"""
        # 初始化两条均线
        self.fast_ma = bt.indicators.ExponentialMovingAverage(
            self.data.close, period=self.p.fast_period)
        self.slow_ma = bt.indicators.ExponentialMovingAverage(
            self.data.close, period=self.p.slow_period)
        self.slow_ma2 = bt.indicators.ExponentialMovingAverage(
            self.data.close, period=self.p.slow_period2)
        # self.fast_ma = Mytt.MyTT_EMA(self.data,period=self.p.fast_period)
        # self.slow_ma = Mytt.MyTT_EMA(self.data,period=self.p.slow_period)

    def notify_order(self, order):
        super().notify_order(order)
 
    def next(self):
        super().next()
 
        # 检查是否在市场中
        if not self.position:
            # 如果不在市场中，并且快速均线在慢速均线之上，则买入
            if self.fast_ma[0] > self.slow_ma[0]:
                self.log(f'BUY CREATE, {self.data.close[0]:.2f}')
                self.order = self.buy()
        else:
            # 如果在市场中，并且快速均线在慢速均线之下，则卖出
            if self.fast_ma[0] < self.slow_ma[0]:
                self.log(f'SELL CREATE, {self.data.close[0]:.2f}')
                self.order = self.sell()
 
    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        # print(f'{dt.isoformat()}, {txt}')